#!/bin/bash

# 思和智库 - 自动化部署脚本
# 用于 Linux 服务器的自动部署

set -e  # 遇到错误立即退出

echo "=========================================="
echo "思和智库 - 自动化部署脚本"
echo "=========================================="

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# 项目路径（根据实际情况修改）
PROJECT_DIR="/path/to/sihe-think-tank"
BACKEND_DIR="$PROJECT_DIR/backend"
FRONTEND_DIR="$PROJECT_DIR/frontend"

# 备份目录
BACKUP_DIR="$PROJECT_DIR/backups"
TIMESTAMP=$(date +%Y%m%d_%H%M%S)

echo -e "${YELLOW}步骤 1/8: 检查环境...${NC}"
# 检查必要的命令是否存在
command -v git >/dev/null 2>&1 || { echo -e "${RED}❌ Git 未安装${NC}" >&2; exit 1; }
command -v python3 >/dev/null 2>&1 || { echo -e "${RED}❌ Python3 未安装${NC}" >&2; exit 1; }
command -v node >/dev/null 2>&1 || { echo -e "${RED}❌ Node.js 未安装${NC}" >&2; exit 1; }
command -v pm2 >/dev/null 2>&1 || { echo -e "${RED}❌ PM2 未安装${NC}" >&2; exit 1; }
echo -e "${GREEN}✅ 环境检查通过${NC}"

echo -e "\n${YELLOW}步骤 2/8: 创建备份...${NC}"
mkdir -p "$BACKUP_DIR"
if [ -d "$BACKEND_DIR/data" ]; then
    echo "备份数据目录..."
    tar -czf "$BACKUP_DIR/data_$TIMESTAMP.tar.gz" -C "$BACKEND_DIR" data
    echo -e "${GREEN}✅ 数据备份完成: $BACKUP_DIR/data_$TIMESTAMP.tar.gz${NC}"
fi

echo -e "\n${YELLOW}步骤 3/8: 拉取最新代码...${NC}"
cd "$PROJECT_DIR"
git stash
git pull origin master
echo -e "${GREEN}✅ 代码更新完成${NC}"

echo -e "\n${YELLOW}步骤 4/8: 更新后端依赖...${NC}"
cd "$BACKEND_DIR"
source venv/bin/activate
pip install -r requirements.txt --quiet
echo -e "${GREEN}✅ 后端依赖更新完成${NC}"

echo -e "\n${YELLOW}步骤 5/8: 运行后端测试...${NC}"
if python run_tests.py; then
    echo -e "${GREEN}✅ 后端测试通过${NC}"
else
    echo -e "${RED}❌ 后端测试失败！部署中止。${NC}"
    exit 1
fi

echo -e "\n${YELLOW}步骤 6/8: 重启后端服务...${NC}"
pm2 restart sihe-backend || pm2 start "uvicorn app.main:app --host 0.0.0.0 --port 3301" --name sihe-backend
echo -e "${GREEN}✅ 后端服务已重启${NC}"

echo -e "\n${YELLOW}步骤 7/8: 更新前端...${NC}"
cd "$FRONTEND_DIR"
npm install --quiet
npm run build
echo -e "${GREEN}✅ 前端构建完成${NC}"

echo -e "\n${YELLOW}步骤 8/8: 重启前端服务...${NC}"
pm2 restart sihe-frontend || pm2 start npm --name sihe-frontend -- start
echo -e "${GREEN}✅ 前端服务已重启${NC}"

echo -e "\n=========================================="
echo -e "${GREEN}🎉 部署完成！${NC}"
echo -e "=========================================="
echo "后端服务: http://localhost:3301"
echo "前端服务: http://localhost:3000"
echo "备份位置: $BACKUP_DIR/data_$TIMESTAMP.tar.gz"
echo ""
echo "使用 'pm2 status' 查看服务状态"
echo "使用 'pm2 logs sihe-backend' 查看后端日志"
echo "使用 'pm2 logs sihe-frontend' 查看前端日志"

